package com.whmnx.chitchat.ui.chat;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.classic.adapter.CommonRecyclerAdapter;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.adapter.UserAdpter2;
import com.whmnx.chitchat.adapter.UserAdpter4;
import com.whmnx.chitchat.adapter.UserAdpter5;
import com.whmnx.chitchat.base.BaseActivity;
import com.whmnx.chitchat.bean.GroupBean;
import com.whmnx.chitchat.bean.GroupDatailBean;
import com.whmnx.chitchat.bean.MessagePackBean;
import com.whmnx.chitchat.bean.UserBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.MainActivity;
import com.whmnx.chitchat.ui.book.GroupActivity;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author : huang
 * date   : 2020/8/5 0005 17:27
 * version: 1.0
 *
 * @author Administrator
 */
public class AddGroupActivity2 extends BaseActivity {
    @BindView(R.id.rl_user)
    RecyclerView rlUser;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.vLine)
    View vLine;

    @BindView(R.id.message_search)
    EditText query;

    private String ids = "";

    public List<String> paramIds = new ArrayList<>();
    private List<String> paramPhones = new ArrayList<>();
    private int type2;
    private String url, groupId,group_ID;
    private UserAdpter2 userAdpter;
    private UserAdpter5 userAdpter4;
    private List<GroupDatailBean.GroupMembersListBean> groupMembersList = new ArrayList<>();
    private String groupMembers_userID;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.add_group_activity);
        setTitle("选择联系人");
        setRringTitle("确定");
        setLeftTitle(View.VISIBLE);
        setIbBack(View.GONE);
        tv_right.setOnClickListener(v -> postAddGroup());

        query.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击搜索的时候隐藏软键盘
                // hideKeyboard(EditText);
                // 在这里写搜索的操作,一般都是网络请求数据
                if (!TextUtils.isEmpty(v.getText().toString().trim())) {
                    search(v.getText().toString().trim());
                }
                return true;
            }
            return false;
        });
    }

    /**
     * 创建群
     */
    private void postAddGroup() {
        if (type2 == 2 || type2 == 1 || type2 == 6){
                if (paramIds != null && paramIds.size() > 0) {
                    for (String id : paramIds) {
                        ids += id + ",";
                    }
                } else {
                    UItils.showToastSafe("请至少选择1位联系人");
                    return;
                }
        }else if (type2 == 5){
            if (paramIds != null && paramIds.size() > 1) {
              //  paramIds.add(toUserId);
              //  List<String> p = UItils.delRepeat(paramIds);
                for (String id : paramIds) {
                    ids += id + ",";
                }
            } else {
                UItils.showToastSafe("请至少选择2位联系人");
                return;
            }
        }else if (type2 == 3 ){
            if (paramPhones != null && paramPhones.size() > 0) {
                for (String id : paramPhones) {
                    ids += id + ",";
                }
            } else {
                UItils.showToastSafe("请至少选择1位联系人");
                return;
            }
        }else {
            if (paramIds != null && paramIds.size() > 1) {
                for (String id : paramIds) {
                    ids += id + ",";
                }
            } else {
                UItils.showToastSafe("请至少选择2位联系人");
                return;
            }
        }

        Map<String, Object> params = new HashMap<>();
        if (type2 == 1) {
            params.put("UserID", SPUtil.getString(Constants.USERID));
            params.put("FriendIDs", ids.substring(0, ids.length() - 1));
            url = Constants.GETCOMMONLYUSEDFRIEND;
        } else if (type2 == 2) {
            params.put("UserID", SPUtil.getString(Constants.USERID));
            params.put("UserIDs", ids.substring(0, ids.length() - 1));
            params.put("GroupID", groupId);
            url = Constants.POSTADDGROUPMEMBERS;
            //移除
        } else if (type2 == 3){
            params.put("Mobile", SPUtil.getString(Constants.PHONE));
            params.put("FriendMobile", ids.substring(0, ids.length() - 1));
            url = Constants.GETREMOVEBLOCKFRIEND;
        }else if (type2 == 6){
          //  params.put("GroupID", groupId);
          //  url = Constants.GETGROUPMENBERSBYGROUPID;
        }else {
            params.put("CreateUserID", SPUtil.getString(Constants.USERID));
            params.put("UserIDs", ids.substring(0, ids.length() - 1));
            url = Constants.POSTADDGROUP;
        }

        if (type2 == 3){
            HttpClient.get(AddGroupActivity2.this, url, params, new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean result) {
                    UItils.showToastSafe("移除黑名单成功");
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.HEI);
                    EventBus.getDefault().post(messageEvent);
                    finish();
                }
            });
        }else if (type2 == 6){

            UUID uuid = UUID.randomUUID();
            MessagePackBean messagePackBean = new MessagePackBean();
            messagePackBean.setID(uuid.toString());
            messagePackBean.setGroupID(groupId);
            messagePackBean.setType(4);
            messagePackBean.setRecordType(0);
            messagePackBean.setMessage("");
            messagePackBean.setSendId(SPUtil.getString(Constants.USERID));
            messagePackBean.setReceiveId(groupMembers_userID);
            MainActivity.reliableClient.send("GetDeleteGroupMenbers", messagePackBean);

            finish();


          /*  Map<String, Object> params2 = new HashMap<>();
            params2.put("GroupID",groupId);
            params2.put("UserID",SPUtil.getString(Constants.USERID));
            params2.put("DeleteUserID",ids.substring(0, ids.length() - 1));
            HttpClient.get(AddGroupActivity.this, Constants.GETDELETEGROUPMENBERS, params2, new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean result) {
                    UItils.showToastSafe("删除群成员成功");
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.ADDFRIENDS);
                    EventBus.getDefault().post(messageEvent);
                }
            });*/
        }else if (type2 == 1) {
            HttpClient.post2(AddGroupActivity2.this, Constants.GETCOMMONLYUSEDFRIEND, params, new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean result) {
                        UItils.showToastSafe("添加常用好友成功");
                        MessageEvent messageEvent = new MessageEvent();
                        messageEvent.setMessageKey(EventConstants.FRIENDS);
                        EventBus.getDefault().post(messageEvent);
                    finish();
                }
            });
        }else {
            if (type2 == 2) {
             //   UItils.showToastSafe("添加群成员成功");
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.ADDFRIENDS);
               // EventBus.getDefault().post(messageEvent);


                UUID uuid = UUID.randomUUID();
                MessagePackBean messagePackBean = new MessagePackBean();
                messagePackBean.setID(uuid.toString());
                messagePackBean.setGroupID(groupId);
                messagePackBean.setType(4);
                messagePackBean.setRecordType(0);
                messagePackBean.setMessage("");
                messagePackBean.setSendId(SPUtil.getString(Constants.USERID));
                messagePackBean.setReceiveId(ids.substring(0, ids.length() - 1));
                MainActivity.reliableClient.send("PostAddGroupMembers", messagePackBean);
                finish();

            } else {
                UItils.showToastSafe("创建群组成功");

                UUID uuid = UUID.randomUUID();
                MessagePackBean messagePackBean = new MessagePackBean();
                messagePackBean.setID(uuid.toString());
                messagePackBean.setGroupID("");
                messagePackBean.setType(4);
                messagePackBean.setRecordType(0);
                messagePackBean.setMessage("");
                messagePackBean.setSendId(SPUtil.getString(Constants.USERID));
                messagePackBean.setReceiveId(ids.substring(0, ids.length() - 1));
                MainActivity.reliableClient.send("PostAddGroup", messagePackBean);

                MessageEvent messageEvent = new MessageEvent();
                //刷新消息 列表
                messageEvent.setMessageKey(EventConstants.SENDMSG);
              //  EventBus.getDefault().post(messageEvent);

                finish();

            }
        }
    }


    @Override
    protected void loadData() {
        type2 = getIntent().getIntExtra("type", 0);
        if (type2 == 3)setRringTitle("移除黑名单");
        groupId = getIntent().getStringExtra("group_id");
        paramIds.clear();
        paramPhones.clear();

        if (type2 != 6) {
            rlUser.setLayoutManager(new LinearLayoutManager(this));
            userAdpter = new UserAdpter2(this);
            rlUser.setItemAnimator(new DefaultItemAnimator());
            rlUser.setAdapter(userAdpter);
        }


        if (type2 == 1) {
            tvNum.setVisibility(View.GONE);
            vLine.setVisibility(View.GONE);
        }


        Map<String, Object> params = new HashMap<>();
        params.put("UserID", SPUtil.getString(Constants.USERID));
        //好友
        if (type2 == 1) {
            params.put("Type", "1");
        } else if (type2 == 3){
            params.put("Type", "3");
        }else {
            params.put("Type", "-2");  //普通好友 + 常用好友
        }


        if (type2 == 6){
            rlUser.setLayoutManager(new LinearLayoutManager(this));
            rlUser.setItemAnimator(new DefaultItemAnimator());
            userAdpter4 = new UserAdpter5(this);
            rlUser.setAdapter(userAdpter4);

            Map<String, Object> params2 = new HashMap<>();
            params2.put("GroupID", getIntent().getStringExtra("group_id"));
            HttpClient.get(AddGroupActivity2.this, Constants.GETGROUPMENBERSBYGROUPID, params2, new CallBack<GroupDatailBean>() {
                @Override
                public void onSuccess(GroupDatailBean result) {
                    groupMembersList.clear();
                    String userId = SPUtil.getString(Constants.USERID);
                    groupMembersList.addAll(result.getGroupMembersList());
                    for (GroupDatailBean.GroupMembersListBean groupMembersListBean : result.getGroupMembersList()) {
                        if (groupMembersListBean.getGroupMembers_UserID().equals(userId)){
                            groupMembersList.remove(groupMembersListBean);
                        }
                    }
                    userAdpter4.replaceAll(groupMembersList);
                }
            });

             userAdpter4.setOnItemClickListener((viewHolder, view, i) -> {
                 groupMembers_userID = userAdpter4.getItem(i).getGroupMembers_UserID();
                 if (params.size() > 0)paramIds.remove(userAdpter4.getItem(i).getGroupMembers_UserID());
                 for (GroupDatailBean.GroupMembersListBean datum : groupMembersList) {
                     datum.setSelect(false);
                 }

                 userAdpter4.getItem(i).setSelect(true);
                 userAdpter4.notifyDataSetChanged();
                 paramIds.add(userAdpter4.getItem(i).getGroupMembers_UserID());
             });

        }else {
            HttpClient.get(AddGroupActivity2.this, Constants.GETFRIENDLIST, params, new CallBack<List<UserBean>>() {
                @Override
                public void onSuccess(List<UserBean> result) {
                    userAdpter.addAll(result);
                }
            });


            userAdpter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                    ImageView ivSelect = view.findViewById(R.id.iv_select);

                    if (ivSelect.isSelected() == false){
                        ivSelect.setSelected(true);
                        ivSelect.setImageResource(R.mipmap.ic_select);  //ic_no_select
                        // map.put(position,rechargeList.get(position).getRecharge_Money() + "");//添加
                    }else {
                        ivSelect.setSelected(false);
                        ivSelect.setImageResource(R.mipmap.ic_no_select);
                    }
                  /*  if (userAdpter.getItem(i).isSelect()) {
                        userAdpter.getItem(i).setSelect(true);
                        ivSelect.setImageResource(R.mipmap.ic_select);  //ic_no_select
                        paramIds.remove(userAdpter.getItem(i).UserID);
                        paramPhones.remove(userAdpter.getItem(i).Moblie);
                    } else {
                        userAdpter.getItem(i).setSelect(false);
                        ivSelect.setImageResource(R.mipmap.ic_no_select);
                        paramIds.add(userAdpter.getItem(i).UserID);
                        paramPhones.add(userAdpter.getItem(i).Moblie);
                    }*/
                }
            });
        }
    }

    private void search(String trim) {
        Map<String, Object> params = new HashMap<>();
        params.put("Con", trim);
        params.put("UserID", SPUtil.getString(Constants.USERID));
        //好友
        if (type2 == 1) {
            params.put("Type", "1");
        } else if (type2 == 3) {
            params.put("Type", "3");
        } else {
            params.put("Type", "-2");
        }

            HttpClient.get(AddGroupActivity2.this, Constants.GETSEATCHFRIENDLIST, params, new CallBack<List<UserBean>>() {
                @Override
                public void onSuccess(List<UserBean> result) {
                    if (result.size() == 0){
                        UItils.showToastSafe("未搜索到相关联系人");
                        return;
                    }
                    userAdpter.replaceAll(result, true);
                }
            });
        }



    @OnClick(R.id.tv_num)
    public void onViewClicked() {
        Intent intentCamera = new Intent();
        intentCamera.setClass(this, GroupActivity.class);
        intentCamera.putExtra("type", 1);
        startActivityForResult(intentCamera, 200);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == 200){
                GroupBean groupBean = (GroupBean)data.getSerializableExtra("group");
                tvNum.setText(groupBean.getGroup_Name());
                group_ID =  groupBean.getGroup_ID();
            }
        }
    }
}
